package dao;

import java.util.List;

import hibernate.HibernateUtil;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import entities.ProveedorEntity;


public class HibernateProveedorBeanDAO 
{
	private static HibernateProveedorBeanDAO instancia = null;
	private static SessionFactory sf = null;

	public static HibernateProveedorBeanDAO getInstancia()
	{
		if(instancia == null)
		{
			sf = HibernateUtil.getSessionFactory();
			instancia = new HibernateProveedorBeanDAO();
		} 
		return instancia;
	}

	public void grabarProveedor(ProveedorEntity nuevoProveedor ) 
	{
		Session session = sf.openSession();
		session.beginTransaction();
		
		session.persist(nuevoProveedor);
		
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public void eliminarProveedor( ProveedorEntity proveedor )
	{
		Session session = sf.openSession();
		session.beginTransaction();
		
		session.delete( proveedor );
		
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public void modificarProveedor( ProveedorEntity proveedor )
	{
		Session session = sf.openSession();
		session.beginTransaction();
		
		session.update( proveedor );
		
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public ProveedorEntity obtenerProveedorPorCUIT( String CUIT )
	{
		Session session=sf.openSession();
		
		Query query=session.createQuery("from ProveedorBean p where p.estado = true and p.CUIT = :cuit");
		query.setParameter("cuit", CUIT);
		
		@SuppressWarnings("unchecked")
		List<ProveedorEntity> proveedor = query.list();
		
		session.close();
		return proveedor.get(0);
	}
}
